package com.cskaoyan.service;

import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.bo.OrderSearchBo;
import com.cskaoyan.bean.entity.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.controller.wx.WxShowOrderStatusVo;
import com.cskaoyan.exception.OrderSubmitException;
import com.cskaoyan.mapper.*;
import com.cskaoyan.bean.entity.Comment;
import com.cskaoyan.bean.entity.Order;
import com.cskaoyan.bean.entity.OrderExample;
import com.cskaoyan.utils.*;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;



@Service
public class OrderServiceImpl implements OrderService{

    private static final int BUYBYCART = 0;
    private static final String FREIGHT_MIN = "market_express_freight_min";
    private static final String FREIGHT_VALUE = "market_express_freight_value";
    private static final int COMPARE_VALUE = -1;
    private static final int NOT_USE = -1;

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    CommentMapper commentMapper;

    // 快递公司的Mapper
    @Autowired
    ChannelMapper channelMapper;

    // 订单商品连接的Mapper
    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    // 用户的Mapper
    @Autowired
    UserMapper userMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    SystemMapper systemMapper;

    @Autowired
    CouponMapper couponMapper;

    @SneakyThrows
    @Override
    public BasePageData<Order> query(BaseParam baseParam, OrderSearchBo orderSearchBo) {
        OrderExample orderExample = new OrderExample();

        OrderExample.Criteria criteria = orderExample.createCriteria();

        // 配置分页
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());

        // 如果开始从start查询的时间或到end结束的时间不为空，就拼接条件
//        StringToDateTypeHandler stringToDateTypeHandler = new StringToDateTypeHandler();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 起始时间
        if(orderSearchBo.getStart() != null && !orderSearchBo.getStart().equals("")){
            criteria.andAddTimeGreaterThanOrEqualTo(simpleDateFormat.parse(orderSearchBo.getStart()));
        }
        // 终止时间
        if(orderSearchBo.getEnd() != null && !orderSearchBo.getEnd().equals("")){
            criteria.andEndTimeLessThanOrEqualTo(simpleDateFormat.parse(orderSearchBo.getEnd()));
        }
        // 订单编号
        if(orderSearchBo.getOrderSn() != null && !orderSearchBo.getOrderSn().equals("")){
            criteria.andOrderSnEqualTo(orderSearchBo.getOrderSn());
        }
        // 订单状态
        if(orderSearchBo.getOrderStatusArray() != null && !orderSearchBo.getOrderStatusArray().equals("")){
            criteria.andOrderStatusIn(orderSearchBo.getOrderStatusArray());
        }

        // 设置排序
        orderExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());

        // 根据条件查询order
        List<Order> orders = orderMapper.selectByExample(orderExample);
        return BasePageData.ok(orders);
    }

    //回复商品评论
    @Override
    public int addreply(Comment comment) {
        Comment cm = new Comment();
        cm.setContent(comment.getContent());
        return commentMapper.insertSelective(cm);

    }

    @Override
    public List<Channel> getChannel() {
        ChannelExample channelExample = new ChannelExample();
        ChannelExample.Criteria criteria = channelExample.createCriteria();

        List<Channel> channelList = channelMapper.selectByExample(channelExample);
        return channelList;
    }

    @Override
    public OrderDetailVo detail(Integer id) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria orderGoodsCriteria = orderGoodsExample.createCriteria();

        if(id != null && !id.equals("")){
            orderGoodsCriteria.andOrderIdEqualTo(id);
        }
        // 查询orderGoods信息
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        // 查询order信息
        Order order = orderMapper.selectByPrimaryKey(id);

        // 利用用户id获取用户信息
        User user = userMapper.selectByPrimaryKey(order.getUserId());

        OrderDetailVo orderDetailVo = new OrderDetailVo(orderGoodsList, user, order);

        return orderDetailVo;
    }

    @Override
    public void delete(Integer id) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria orderGoodsCriteria = orderGoodsExample.createCriteria();
        if (id != null) {
            orderGoodsCriteria.andOrderIdEqualTo(id);
        }
        // 删除订单
        orderMapper.deleteByPrimaryKey(id);
        // 删除订单商品中对应的订单记录
        orderGoodsMapper.deleteByExample(orderGoodsExample);
    }

    // =======================================前台=======================================

    @Override
    public BasePageData queryList(WxOrderListReqBo wxOrderListReqBo) {
        // 配置分页
        MarketPageUtil.startPage(wxOrderListReqBo);
        Short showType = wxOrderListReqBo.getShowType();
        Short status = null;
        // 判断每个标题对应的订单状态
        if (showType == 0) {
            // 二者都为null  查询全部
            showType = null;
        } else if (showType == 1) {
            // 待付款
            showType = OrderStatus.UN_PAID.getCode();
        } else if (showType == 2) {
            // 待发货
            showType = OrderStatus.PAID.getCode();
        } else if (showType == 3) {
            // 待收货
            showType = OrderStatus.SHIPPED.getCode();
        } else if (showType == 4) {
            // 待评价（用户收货/系统自动收货）
            showType = OrderStatus.USER_RECEIVED.getCode();
            status = OrderStatus.SYSTEM_RECEIVED.getCode();
        }
        // 查询订单信息及对应订单商品信息
        List<WxOrderListRespVo> wxOrderListRespVos = orderMapper.selectOrderListByStatus(showType,status);
        // 给HandleOption赋值  每个订单状态下有不同的按钮
        for (WxOrderListRespVo wxOrderListRespVo : wxOrderListRespVos) {
            wxOrderListRespVo.setWxHandleOption(WxHandleOption.setValue(wxOrderListRespVo.getOrderStatusText()));
        }
        return BasePageData.ok(wxOrderListRespVos);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WxOrderDetailVo queryOrderDetail(Integer orderId) {
        // 根据订单id查询对应的订单信息
        Order order = orderMapper.selectByPrimaryKey(orderId);
        WxOrderInfoInOrderDetailVo orderInfo = new WxOrderInfoInOrderDetailVo(order.getConsignee(),order.getAddress(),
                order.getAddTime(),order.getOrderSn(),order.getActualPrice(),order.getMobile(),order.getMessage(),
                order.getAftersaleStatus(),order.getGoodsPrice(),order.getCouponPrice(), order.getId(),order.getFreightPrice());
        orderInfo.setOrderStatus(order.getOrderStatus());
        // 获取当前订单的订单状态描述
        String orderStatusText = orderInfo.getOrderStatusText();
        // 通过订单状态描述给HandleOption赋值
        orderInfo.setHandleOption(WxHandleOption.setValue(orderStatusText));
        // 根据订单id查询订单商品信息
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andOrderIdEqualTo(orderId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        WxOrderDetailVo wxOrderDetailVo = new WxOrderDetailVo();
        wxOrderDetailVo.setOrderInfo(orderInfo);
        wxOrderDetailVo.setOrderGoods(orderGoods);
        return wxOrderDetailVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertComment(WxOrderCommentBo wxOrderCommentBo) {
        // 查询订单商品信息
        OrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(wxOrderCommentBo.getOrderGoodsId());
        // 查询订单对应的用户id
        Integer userId = orderMapper.selectUserIdByOrderId(orderGoods.getOrderId());
        // 在market_comment表中插入一条评论
        Comment comment = new Comment();
        comment.setValueId(orderGoods.getGoodsId());
        comment.setContent(wxOrderCommentBo.getContent());
        comment.setUserId(userId);
        comment.setHasPicture(wxOrderCommentBo.getHasPicture());
        comment.setPicUrls(wxOrderCommentBo.getPicUrls());
        comment.setStar(wxOrderCommentBo.getStar());
        int affectedRows = commentMapper.insertGoodsComment(comment);
        if (affectedRows == 1) {
            // 根据orderGoodsId去修改comment（改成评论id）和update_time
            orderGoodsMapper.updateCommentByOrderGoodsId(comment.getId(),wxOrderCommentBo.getOrderGoodsId());
            // 根据订单id修改market_order的comments和订单状态
            orderMapper.updateCommentsByOrderId(OrderStatus.COMMENTED.getCode(),orderGoods.getOrderId());
            return Constant.SUCCESS;
        }
        return Constant.FAIL;
    }

    @Override
    public WxUserIndexVo getUserIndex(Integer userId) {

        // 未付款 101
        Integer unpaidNum = orderMapper.selectUnpaidOrderNumByOrderStatus("101");

        // 待发货 201
        OrderExample unshipExample = GetDiffOrderExampleAccordingToOrderStatusUtil.getStatusExample(userId, "201");
        OrderExample.Criteria unshipExampleCriteria = unshipExample.createCriteria();
        unshipExampleCriteria.andDeletedEqualTo(false);
        List<Order> unshipList = orderMapper.selectByExample(unshipExample);
        Integer unshipNum = unshipList.size();

        // 待收货 301
        OrderExample unrecvExample = GetDiffOrderExampleAccordingToOrderStatusUtil.getStatusExample(userId, "402");
        OrderExample.Criteria unrecvExampleCriteria = unrecvExample.createCriteria();
        unrecvExampleCriteria.andDeletedEqualTo(false);
        List<Order> unrecvList = orderMapper.selectByExample(unrecvExample);
        Integer unrecvNum = unrecvList.size();

        // 待评价 401 402
        OrderExample uncommentExample = new OrderExample();
        OrderExample.Criteria uncommentExampleCriteria = uncommentExample.createCriteria();
        uncommentExampleCriteria.andDeletedEqualTo(false);
        List<Order> uncommentList = orderMapper.selectUnCommentNumByOrderStatus("401","402");
        Integer uncommentNum = 0;
        for (Order uncommentOrder : uncommentList) {
            uncommentNum += uncommentOrder.getComments();
        }

        WxShowOrderStatusVo showOrderStatusVo = new WxShowOrderStatusVo(unrecvNum, uncommentNum, unpaidNum, unshipNum);
        WxUserIndexVo wxUserIndexVo = new WxUserIndexVo(showOrderStatusVo);
        return wxUserIndexVo;

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateOrderCancel(WxOrderIdBo wxOrderIdBo) {
        // TODO 修改订单状态  未付款（101）  →  已取消（102）  订单关闭
        Order order = new Order();
        order.setId(wxOrderIdBo.getOrderId());
        order.setOrderStatus(OrderStatus.USER_CANCEL.getCode());
        order.setEndTime(new Date());
        int affectedRows = orderMapper.updateOrderStatusByOrderId(OrderStatus.UN_PAID.getCode(),order);
        if (affectedRows == 1) {
            // TODO 更新库存数量
            // 查询订单对应所有商品的list
            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectOrderGoodsListByOrderId(wxOrderIdBo.getOrderId());
            // 修改market_goods_product表中对应商品的数量
            for (OrderGoods orderGoods : orderGoodsList) {
                goodsMapper.updateGoodsNumberByProductId(orderGoods.getProductId(),orderGoods.getNumber());
            }
            // TODO 优惠券退回
            // 查询用户id
            Integer userId = orderMapper.selectUserIdByOrderId(wxOrderIdBo.getOrderId());
            // 修改优惠券的状态(1 → 0)，使用时间null，更新时间now()
            // 通过用户id、订单id和使用状态(1)定位使用的优惠券
            couponUserMapper.updateCouponStatus(userId,wxOrderIdBo.getOrderId());
            return Constant.SUCCESS;
        }
        return Constant.FAIL;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateOrderRefund(WxOrderIdBo wxOrderIdBo) {
        // TODO  修改订单状态  已付款（201） → 申请退款（202）
        Order order = new Order();
        order.setId(wxOrderIdBo.getOrderId());
        order.setOrderStatus(OrderStatus.USER_CANCEL.getCode());
        int affectedRows = orderMapper.updateOrderStatusByOrderId(OrderStatus.APPLY_REFUND.getCode(),order);
        if (affectedRows == 1) {
            //TODO 优惠券退回
            Integer userId = orderMapper.selectUserIdByOrderId(wxOrderIdBo.getOrderId());
            couponUserMapper.updateCouponStatus(userId,wxOrderIdBo.getOrderId());
            return Constant.SUCCESS;
        }
        return Constant.FAIL;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateOrderDeleted(WxOrderIdBo wxOrderIdBo) {
        // TODO  逻辑删除订单
        // market_order逻辑删除
        int affectedRows = orderMapper.updateOrderDeleted(wxOrderIdBo.getOrderId());
        if (affectedRows == 1) {
            // 查询订单商品表
            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectOrderGoodsListByOrderId(wxOrderIdBo.getOrderId());
            for (OrderGoods orderGoods : orderGoodsList) {
                // market_order_goods逻辑删除
                orderGoodsMapper.updateOrderGoodsDeleted(wxOrderIdBo.getOrderId());
            }
            return Constant.SUCCESS;
        }
        return Constant.FAIL;
    }

    @Override
    public int updateOrderConfirm(WxOrderIdBo wxOrderIdBo) {
        // TODO  订单状态改变   已发货（301）  →  用户收货（401）
        Order order = new Order();
        order.setId(wxOrderIdBo.getOrderId());
        order.setConfirmTime(new Date());
        order.setOrderStatus(OrderStatus.USER_RECEIVED.getCode());
        int affectedRows = orderMapper.updateOrderStatusByOrderId(OrderStatus.SHIPPED.getCode(),order);
        if (affectedRows == 1) {
            return Constant.SUCCESS;
        }
        return Constant.FAIL;
    }

    @Override
    public OrderGoods queryOrderGoods(Integer orderId, Integer goodsId) {
        OrderGoods orderGoods = orderGoodsMapper.selectOrderGoodsBean(orderId,goodsId);
        return orderGoods;
    }

    // submit  提交订单
    @Override
    public WxOrderSubmitVo insertOrder(WxOrderSubmitBo wxOrderSubmitBo) throws OrderSubmitException {
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        Integer userId = userMapper.selectUserIdByUserName(username);
        // 获取唯一的订单号
        String preOrderSn = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String orderSn = preOrderSn +  (int) ((Math.random() * 9 + 1) * 100000);
        int count = orderMapper.selectOrderSnUnique(orderSn);
        while (count != 0) {
            orderSn = preOrderSn +  (int) ((Math.random() * 9 + 1) * 100000);
            count = orderMapper.selectOrderSnUnique(orderSn);
        }
        Order order = new Order();
        OrderGoods orderGoods = new OrderGoods();
        // 用户名  订单编号 订单状态 售后状态
        order.setUserId(userId);
        order.setOrderSn(orderSn);
        order.setOrderStatus(OrderStatus.UN_PAID.getCode());
        order.setAftersaleStatus(AftersaleStatus.CAN_APPLY.getCode().shortValue());
        // 收件人 手机号  地址
        Address address = addressMapper.selectByPrimaryKey(wxOrderSubmitBo.getAddressId());
        order.setConsignee(address.getName());
        order.setMobile(address.getTel());
        order.setAddress(address.getAddressDetail());
        // 订单留言
        order.setMessage(wxOrderSubmitBo.getMessage());

        // 待评价订单的商品数量
        short comments = 0;
        // 获取商品总费用
        List<Cart> carts = null;
        Cart cart = null;
        BigDecimal goodsPrice = new BigDecimal("0");
        if (wxOrderSubmitBo.getCartId() == BUYBYCART) {
            // 购物车中选中商品的下单
            comments = ((short) carts.size());
            for (Cart cart1 : carts) {
                CartExample cartExample = new CartExample();
                CartExample.Criteria cartExampleCriteria = cartExample.createCriteria();
                cartExampleCriteria.andUserIdEqualTo(userId);
                cartExampleCriteria.andCheckedEqualTo(true);
                cartExampleCriteria.andDeletedEqualTo(false);
                carts = cartMapper.selectByExample(cartExample);
                Integer productId = cart1.getProductId();
                GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
                BigDecimal price = goodsProduct.getPrice();
                // 单价 * 数量
                BigDecimal goodsCountPrice = price.multiply(new BigDecimal(cart1.getNumber()));
                goodsPrice = goodsPrice.add(goodsCountPrice);
            }
        } else {
            // 直接购买下单
            cart = cartMapper.selectByPrimaryKey(wxOrderSubmitBo.getCartId());
            GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(cart.getProductId());
            goodsPrice = goodsProduct.getPrice().multiply(new BigDecimal(goodsProduct.getNumber()));
        }
        order.setGoodsPrice(goodsPrice);

        // 查询运费最低费用并判断是否需要运费
        BigDecimal freightPrice = new BigDecimal("0");
        String freightMin1 = systemMapper.selectFreightMin(FREIGHT_MIN);
        BigDecimal freightMin = new BigDecimal(freightMin1);
        String freightValue1 = systemMapper.selectFreightValue(FREIGHT_VALUE);
        BigDecimal freightValue = new BigDecimal(freightValue1);
        if (goodsPrice.compareTo(freightMin) == COMPARE_VALUE) {
            freightPrice = freightValue;
        }
        order.setFreightPrice(freightPrice);

        // 使用优惠券的减免金额
        BigDecimal couponPrice = new BigDecimal("0");
        if (wxOrderSubmitBo.getCouponId() != NOT_USE) {
            Coupon coupon = couponMapper.selectByPrimaryKey(wxOrderSubmitBo.getCouponId());
            couponPrice = coupon.getDiscount();
        }
        order.setCouponPrice(couponPrice);

        // 团购优惠价
        BigDecimal grouponPrice = new BigDecimal("0");
        order.setGrouponPrice(grouponPrice);

        // 订单金额
        BigDecimal orderPrice = goodsPrice.add(freightPrice).subtract(couponPrice);
        // 实付金额
        BigDecimal integralPrice = new BigDecimal("0");
        BigDecimal actualPrice = orderPrice.subtract(integralPrice);
        order.setIntegralPrice(integralPrice);
        order.setActualPrice(actualPrice);

        // 微信
        User user = userMapper.selectByPrimaryKey(userId);
        order.setPayId(user.getWeixinOpenid());
        order.setPayTime(new Date());

        // 添加修改时间
        order.setAddTime(new Date());
        order.setUpdateTime(new Date());
        order.setComments(comments);
        order.setDeleted(false);

        int code = orderMapper.insertSelective(order);
        if (code != 1) throw new OrderSubmitException();
        Integer orderId = order.getId();

        // 订单商品同步到商品货品表
        if (wxOrderSubmitBo.getCartId() == BUYBYCART) {
            for (Cart cart2 : carts) {
                orderGoodsMapper.insertOrderGoods(orderId,cart2);
            }
        } else {
            orderGoodsMapper.insertOrderGoods(orderId,cart);
        }
        return new WxOrderSubmitVo(orderId);
    }
}
